<?php
namespace App\Socket\Parser;
use EasySwoole\Core\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Core\Socket\Common\CommandBean;

use App\Socket\Controller\WebSocket\Index;
use App\Socket\Model\User;
use App\Socket\Model\Room;
use App\Socket\Error\Error;

class WebSocket implements ParserInterface{
    public static function decode($raw,$client){                
        

        $commandLine = json_decode($raw, true);
        if (!is_array($commandLine)) {
            return 'unknown command';
        }

        
        $CommandBean = new CommandBean();
        $control = isset($commandLine['c']) ? 'App\\Socket\\Controller\\WebSocket\\'. ucfirst($commandLine['c']) : '';
        $action = $commandLine['a'] ?? 'none';
        $data = $commandLine['d'] ?? null;
        //找不到类时访问默认Index类

        $CommandBean->setControllerClass(class_exists($control) ? $control : Index::class);
        $CommandBean->setAction(class_exists($control) ? $action : 'empty');    
        if($data){
            $CommandBean->setArgs($data);
        }
        
        
        /** 对象注入 */
        $fd = $client->getFd();
        $user = User::where("fd",$fd)->find();                  

        $client->setData($user);                        
        return $CommandBean;
    }

    public static function encode(string $raw, $client): ?string
    {
        return $raw;
    }
}

